using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using WorkFlowCore.BusinessDemo.Web.Data;
using WorkFlowCore.BusinessDemo.Web.Entities;
using WorkFlowCore.BusinessDemo.Web.Models;
using System.Collections.Generic;
using System.Linq;

namespace WorkFlowCore.BusinessDemo.Web.Controllers
{
    public class OrganizationController : BaseController
    {
        private readonly BusinessDemoDbContext _context;

        public OrganizationController(BusinessDemoDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> Index()
        {
            var organizations = await _context.Organizations
                .Where(o => o.ParentId == null)
                .ToListAsync();
            
            var viewModels = new List<OrganizationIndexViewModel>();
            foreach (var org in organizations)
            {
                viewModels.Add(await BuildViewModelRecursive(org));
            }
            
            return View(viewModels);
        }

        private async Task<OrganizationIndexViewModel> BuildViewModelRecursive(Organization organization)
        {
            var viewModel = new OrganizationIndexViewModel
            {
                Id = organization.Id,
                Name = organization.Name,
                Description = organization.Description,
                ParentId = organization.ParentId,
                Children = new List<OrganizationIndexViewModel>(),
                Users = await _context.Users
                    .Where(u => u.OrganizationId == organization.Id)
                    .Select(u => new UserViewModel
                    {
                        Id = u.Id,
                        Name = u.Name,
                        EmployeeNumber = u.EmployeeNumber
                    })
                    .ToListAsync()
            };

            await _context.Entry(organization)
                .Collection(o => o.Children)
                .LoadAsync();

            foreach (var child in organization.Children)
            {
                viewModel.Children.Add(await BuildViewModelRecursive(child));
            }

            return viewModel;
        }

        public IActionResult Create(int? parentId)
        {
            return View(new OrganizationCreateViewModel { ParentId = parentId });
        }

        [HttpPost]
        public async Task<IActionResult> Create(OrganizationCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var organization = new Organization
                {
                    Name = model.Name,
                    Description = model.Description,
                    ParentId = model.ParentId
                };

                _context.Add(organization);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(model);
        }

        public async Task<IActionResult> Edit(int id)
        {
            var organization = await _context.Organizations.FindAsync(id);
            if (organization == null)
            {
                return NotFound();
            }

            var model = new OrganizationEditViewModel
            {
                Id = organization.Id,
                Name = organization.Name,
                Description = organization.Description,
                ParentId = organization.ParentId
            };

            // 获取所有可能的父组织（排除自身及其子组织）
            var allOrganizations = await _context.Organizations.ToListAsync();
            var validParents = allOrganizations
                .Where(o => o.Id != id && !IsDescendant(allOrganizations, id, o.Id))
                .Select(o => new SelectListItem
                {
                    Value = o.Id.ToString(),
                    Text = GetOrganizationPath(allOrganizations, o)
                })
                .ToList();

            ViewBag.ParentOrganizations = validParents;

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(int id, OrganizationEditViewModel model)
        {
            if (id != model.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                var organization = await _context.Organizations.FindAsync(id);
                if (organization == null)
                {
                    return NotFound();
                }

                organization.Name = model.Name;
                organization.Description = model.Description;
                organization.ParentId = model.ParentId;
                organization.UpdatedTime = DateTime.Now;

                _context.Update(organization);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(model);
        }

        public async Task<IActionResult> Delete(int id)
        {
            var organization = await _context.Organizations
                .Include(o => o.Children)
                .FirstOrDefaultAsync(o => o.Id == id);
            if (organization == null)
            {
                return NotFound();
            }

            if (organization.Children.Any())
            {
                TempData["ErrorMessage"] = "不能删除包含子组织的组织";
                return RedirectToAction(nameof(Index));
            }

            try
            {
                _context.Organizations.Remove(organization);
                await _context.SaveChangesAsync();
                TempData["SuccessMessage"] = "组织删除成功";
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = $"删除组织失败: {ex.Message}";
            }
            return RedirectToAction(nameof(Index));
        }

        private bool IsDescendant(List<Organization> allOrganizations, int parentId, int childId)
        {
            var current = allOrganizations.FirstOrDefault(o => o.Id == childId);
            while (current != null)
            {
                if (current.ParentId == parentId)
                    return true;
                current = allOrganizations.FirstOrDefault(o => o.Id == current.ParentId);
            }
            return false;
        }

        private string GetOrganizationPath(List<Organization> allOrganizations, Organization org)
        {
            var path = new List<string>();
            var current = org;
            while (current != null)
            {
                path.Add(current.Name);
                current = allOrganizations.FirstOrDefault(o => o.Id == current.ParentId);
            }
            path.Reverse();
            return string.Join(" > ", path);
        }
    }
}
